package com.hxzy.shop.common.redis;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author wxy
 * @Date 2021/3/3 13:47
 * @Version 1.0
 */
@Service
public class RedisServiceImpl implements RedisService {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void emptyToken(String k) {
        Boolean bool = redisTemplate.hasKey(k);
        if (bool) {
            redisTemplate.delete(k);
        }
    }

    @Override
    public void saveToken(String key, String v, int expired) {
        Boolean bool = redisTemplate.hasKey(key);
        if (bool) {
            redisTemplate.delete(key);
        }
        redisTemplate.opsForValue().set(key, v, expired, TimeUnit.SECONDS);
    }

    @Override
    public String getToken(String key) {
        Object o = redisTemplate.opsForValue().get(key);
        if(Objects.nonNull(o)) {
           return String.valueOf(o);
       }
        return null;
    }

    @Override
    public boolean checkAccount(String k, String realToken) {
        Boolean bool = redisTemplate.hasKey(k);
        if (!bool) {
            return false;
        }
        String value = (String) redisTemplate.opsForValue().get(k);
        assert value != null;
        if (!value.equals(realToken)) {
            return false;
        }
        return true;
    }
}
